package com.ruoyi.shop.controller;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;
import java.util.concurrent.TimeUnit;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.che.api.TestService;
import com.ruoyi.common.core.constant.CacheConstants;
import com.ruoyi.common.core.constant.SecurityConstants;
//import com.ruoyi.shop.api.RemoteShopService;
import com.ruoyi.shop.domain.CheShop;
import com.ruoyi.shop.service.ICheShopService;
//import com.ruoyi.sumorder.util.SmsUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.*;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.core.GeoOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.security.annotation.RequiresPermissions;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.core.web.page.TableDataInfo;

/**
 * 商户管理Controller
 *
 * @author ruoyi
 * @date 2025-01-02
 */
@RestController
@RequestMapping("/manage")
public class CheShopController extends BaseController {
    @Autowired
    private ICheShopService cheShopService;

    //  查找附近门店    --  Redis --GeoSpacial
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    private static final String GEO_KEY = "shops:"; // Redis中存储加油站Geo数据的key

    //  找附近的加油站  按距离排序
    @RequiresPermissions("shop:manage:list")
    @GetMapping("/listAround")
    public TableDataInfo listAround(@RequestParam("longitude") String longitude,
                                    @RequestParam("latitude") String latitude,
                                    @RequestParam("dt") String dt,
                                    @RequestParam("id") Long id
    )
    {
        //  以经纬度为中心，半径为10km的圆，用作后续搜索的条件
        Circle within = new Circle(new Point(Double.valueOf(longitude), Double.valueOf(latitude)) , new Distance(Double.valueOf(dt), Metrics.KILOMETERS));


        // 查找附近的加油站
        GeoResults<RedisGeoCommands.GeoLocation<String>> radius = redisTemplate.opsForGeo().radius(
                GEO_KEY+id, within,
                RedisGeoCommands.GeoRadiusCommandArgs.newGeoRadiusArgs().sortAscending().includeDistance());//  搜索规则

        //  将redis中排序完成的数据保存到Map集合中
        List<HashMap<String,Double>> rs = new ArrayList<>();
        radius.forEach(r -> {
            String name = r.getContent().getName();
//            System.out.println(name);
            double distance = r.getDistance().getValue()*1000;
            HashMap<String, Double> mp = new HashMap<>();
            mp.put(name,distance);
            rs.add(mp);
        });

        return getDataTable(rs);

    }

    @RequiresPermissions("shop:manage:list")
    @GetMapping("/listGeo/{id}/{name}")
    public TableDataInfo listGeo(@PathVariable Long id) {
//        AjaxResult str = testService.getInfo(1L, "测试请求微服务api接口");
//        System.out.println(str);
        startPage();
        List<CheShop> list = cheShopService.selectCheShopList(null);

        redisTemplate.delete(GEO_KEY+id);
        //  创建Geo,将所有的加油站数据放到Redis里面去
        GeoOperations<String, String> geoOps = redisTemplate.opsForGeo();
        for (CheShop cs : list) {
            //  将经纬度和加油站的id作为识别放入Redis
            if(cs.getLongitude()!=null && cs.getLatitude()!=null){
                Double longitude = cs.getLongitude();
                Double latitude = cs.getLatitude();
                String idd = String.valueOf(cs.getId());
                geoOps.add(GEO_KEY+id, new Point(longitude,latitude ),idd );
            }
        }
        return getDataTable(list);
    }



    @GetMapping("/findByPhone/{phone}")
    public AjaxResult findByPhone(@PathVariable("phone") String phone) {
        return success(cheShopService.selectCheShopByPhone(phone));
    }



    /**
     * 查询商户管理列表
     */
    @RequiresPermissions("shop:manage:list")
    @GetMapping("/list")
    public TableDataInfo list(CheShop cheShop) {
//        AjaxResult str = testService.getInfo(1L, "测试请求微服务api接口");
//        System.out.println(str);
        startPage();
        List<CheShop> list = cheShopService.selectCheShopList(cheShop);
        return getDataTable(list);
    }

    /**
     * 查询商户排名列表
     */
    @RequiresPermissions("shop:manage:list")
    @GetMapping("/rank")
    public TableDataInfo list() {
        startPage();
        List<CheShop> list = cheShopService.selectCheShopRank();
        return getDataTable(list);
    }

    /**
     * 导出商户管理列表
     */
    @RequiresPermissions("shop:manage:export")
    @Log(title = "商户管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, CheShop cheShop) {
        List<CheShop> list = cheShopService.selectCheShopList(cheShop);
        ExcelUtil<CheShop> util = new ExcelUtil<CheShop>(CheShop.class);
        util.exportExcel(response, list, "商户管理数据");
    }

    /**
     * 获取商户管理详细信息
     */
    @RequiresPermissions("shop:manage:query")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {

        return success(cheShopService.selectCheShopById(id));
    }

    /**
     * 新增商户管理
     */
    @RequiresPermissions("shop:manage:add")
    @Log(title = "商户管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody CheShop cheShop) {
        return toAjax(cheShopService.insertCheShop(cheShop));
    }

    /**
     * 修改商户管理
     */
    @RequiresPermissions("shop:manage:edit")
    @Log(title = "商户管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody CheShop cheShop) {
        return toAjax(cheShopService.updateCheShop(cheShop));
    }

    /**
     * 删除商户管理
     */
    @RequiresPermissions("shop:manage:remove")
    @Log(title = "商户管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(cheShopService.deleteCheShopByIds(ids));
    }
}
